package com.codeoss.module.res.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.view.model.HierarchyData;
import com.codeoss.framework.view.util.DataSourceUtil;
import com.codeoss.module.ir.service.IIrMenuService;
import com.codeoss.module.res.model.ResRelRoleMenu;
import com.codeoss.module.res.request.RelRoleMenuPageRequest;
import com.codeoss.module.res.response.RelRoleMenuPageResponse;
import com.codeoss.module.res.service.IRelRoleMenuPageService;
import com.codeoss.module.res.service.IResRelRoleMenuService;

@Service
public class RelRoleMenuPageService implements IRelRoleMenuPageService {
    @Autowired
    private IIrMenuService irMenuService;
    @Autowired
    private IResRelRoleMenuService resRelRoleMenuService;
    @Autowired
	private DataSourceUtil dataSourceUtil;
	@Override
	public RelRoleMenuPageResponse init(Long resRoleId) {
		// TODO Auto-generated method stub
		RelRoleMenuPageResponse relRoleMenuPageResponse=new RelRoleMenuPageResponse();
		YunContext yunContext=YunContext.getCurrentContext();
		List<Map<String, Object>> dataList= irMenuService.listMaps();
		HierarchyData  menuData=dataSourceUtil.convertTableDataToHierarchyData(yunContext, dataList);
		relRoleMenuPageResponse.setMenuData(menuData);
		
		List<Long> valueList=resRelRoleMenuService.getMenuIdListByRoleId(resRoleId);
		relRoleMenuPageResponse.setValueList(valueList);
		
		return relRoleMenuPageResponse;
	}
	@Override
	@Transactional
	public RelRoleMenuPageResponse dataSave(RelRoleMenuPageRequest request) {
		// TODO Auto-generated method stub
		RelRoleMenuPageResponse relRoleMenuPageResponse=new RelRoleMenuPageResponse();
		QueryWrapper<ResRelRoleMenu> queryWrapper=new QueryWrapper<ResRelRoleMenu>();
		queryWrapper.eq("res_role_id", request.getResRoleId());
		resRelRoleMenuService.remove(queryWrapper);
		List<Long> valueList=request.getValueList();
		if(valueList!=null) {
			for(int i=0;i<valueList.size();i++) {
				ResRelRoleMenu resRelRoleMenu=new ResRelRoleMenu();
				resRelRoleMenu.setResRoleId(request.getResRoleId());
				resRelRoleMenu.setIrMenuId(valueList.get(i));
				resRelRoleMenuService.insert(resRelRoleMenu);
			}
		}
		return relRoleMenuPageResponse;
	}

}
